package
{
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.ui.Keyboard;
	
	public class Terminal
	{
		private var m_terminalShown:Boolean = false;
		
		private var m_stage:Stage;
		private var m_display:Sprite = new Sprite();
		private var m_background:Sprite;
		private var m_commandLine:TextField = new TextField();
		private var m_textField:TextField = new TextField();
		private var m_inputBuffer:String = '';
		private var m_callback:Function;
		public function Terminal(stage:Stage, callback:Function)
		{
			m_callback = callback;
			m_stage = stage;
			m_background = Util.getRectSprite(stage.width,stage.height/2,0,.5);
			m_commandLine.defaultTextFormat = new TextFormat(null,12,0xffffff);
			m_commandLine.autoSize = TextFieldAutoSize.LEFT;
			
			m_textField.defaultTextFormat = new TextFormat(null, 12, 0xffff00);
			m_textField.y = m_commandLine.height*1.5;
			m_commandLine.text = '> ';
			
			m_display.addChild(m_background);
			m_display.addChild(m_commandLine);
			m_display.addChild(m_textField);
			m_display.visible = false;
			
			stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			stage.addChild(m_display);
		}
		
		
		private function onKeyUp(ke:KeyboardEvent):void{
			if(ke.keyCode == Keyboard.ENTER){
				m_callback(m_inputBuffer);
				write(m_inputBuffer);
				m_inputBuffer = '';
			} else {
				switch(String.fromCharCode(ke.charCode)){
					case "`":
					case "~":
						this.toggleTerminal();
						break;
					default:
						m_inputBuffer += String.fromCharCode(ke.charCode);
						break;
				}
			}
			
			updateCommandLine();
		}               
		
		private function write(text:String):void{
			m_textField.text = text + "\n" + m_textField.text;
			m_textField.autoSize = TextFieldAutoSize.LEFT;
		}
		
		private function updateCommandLine():void{
			m_commandLine.text = '> ' + m_inputBuffer;
		}
		
		public function toggleTerminal():void{
			if(m_terminalShown){
				this.hideTerminal();
			} else {
				this.showTerminal();
			}
		}
		
		public function hideTerminal():void{
			m_terminalShown = false;
			m_display.visible = false;
		}
		
		public function showTerminal():void{
			m_terminalShown = true;
			m_display.visible = true;
		}
	}
}